package com.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.bean.Role;
import com.mall.bean.RoleExample;
import com.mall.dao.PermissionMapper;
import com.mall.dao.RoleMapper;
import com.mall.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lwd1513
 * @date 2022-04-25 16 33
 * discription
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public int insert(Role role) {
        return 0;
    }

    @Override
    public List<Role> queryData(Role role) {
        return null;
    }

    @Override
    public int update(Role role) {
        return 0;
    }

    @Override
    public int deleteById(String id) {
        return 0;
    }

    @Override
    public Role queryDataById(String id) {
        return null;
    }

    @Override
    public PageInfo<Role> queryDataByPage(int currentPage, int pageSize, Role role) {
        PageHelper.startPage(currentPage, pageSize);
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();

        if (role.getRole_name() != null) {
            criteria.andRole_nameLike("%" + role.getRole_name() + "%");
        }
        List<Role> roles = roleMapper.selectByExampleDef(example);

        PageInfo<Role> rolePageInfo = new PageInfo<>(roles);

        return rolePageInfo;
    }

    @Override
    public List<Role> getRoleList() {
        RoleExample example = new RoleExample();
        return roleMapper.selectByExample(example);
    }

    /**
     * 为角色分配权限
     *
     * @param roleId
     * @param pidArray
     * @return
     */
    @Override
    public int confirmAssignPermission(Integer roleId, String[] pidArray) {

        //移除原先分配的全新
        int res = roleMapper.removeBeforePermissions(roleId);

        //然后挨个添加新的权限进去
        int res2 = roleMapper.addPermissions(roleId,pidArray);
        return res2;
    }

    /**
     * 删除角色 同时删除该角色关联的权限
     *
     * @param roleId
     * @return
     */
    @Override
    public int deleteRoleById(Integer roleId) {
        //先删除该角色关联的权限
        int res = roleMapper.removeBeforePermissions(roleId);

        int res2 = roleMapper.deleteByPrimaryKey(roleId);

        return 0;
    }

    @Override
    public int updateRoleById(Role role) {
        int res = roleMapper.updateByPrimaryKey(role);
        return res;
    }

    @Override
    public int saveRole(Role role) {
        int res = roleMapper.insertSelective(role);
        return res;
    }
}
